"""流程任务定义模型

在流程部署阶段解析 BPMN XML，将 startEvent、userTask、endEvent 及其条件保存，
后续查询申请详情时直接读取，避免实时解析 XML。
"""
from datetime import datetime
from app import db


class ProcessTaskDefinition(db.Model):
    __tablename__ = 'mx_process_task_definitions'

    id = db.Column(db.Integer, primary_key=True)
    process_definition_id = db.Column(db.String(128), index=True, nullable=False, comment='Flowable 流程定义 ID')
    activity_id = db.Column(db.String(128), nullable=False, comment='BPMN 节点 ID')
    activity_name = db.Column(db.String(256), nullable=True, comment='BPMN 节点名称')
    activity_type = db.Column(db.String(32), nullable=False, comment='节点类型: startEvent, userTask, endEvent')
    sequence_index = db.Column(db.Integer, nullable=False, default=0, comment='解析顺序，便于展示未来步骤')
    conditions_json = db.Column(db.Text, nullable=True, comment='进入该节点的条件表达式列表(JSON)')
    assignee = db.Column(db.String(256), nullable=True, comment='Flowable 节点执行人表达式')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    __table_args__ = (
        db.UniqueConstraint('process_definition_id', 'activity_id', name='uq_procdef_activity'),
    )

    def to_dict(self):
        import json
        try:
            conditions = json.loads(self.conditions_json) if self.conditions_json else []
        except Exception:
            conditions = []
        return {
            'process_definition_id': self.process_definition_id,
            'activity_id': self.activity_id,
            'activity_name': self.activity_name,
            'activity_type': self.activity_type,
            'sequence_index': self.sequence_index,
            'conditions': conditions,
            'assignee': self.assignee
        }